package com.tianji.promotion.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.tianji.common.constants.CacheConstant.LOCK_PREFIX;

@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 加锁
     * */
    public boolean tryLock(String lockName,long expire, TimeUnit timeUnit){
        return redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX+lockName, Thread.currentThread().getName(), expire, timeUnit);
    }

    /**
     * 解锁
     * */
    public void unlock(String lockName){
        redisTemplate.delete(LOCK_PREFIX + lockName);
    }


}
